package com.common.code;




import com.common.entity.MessageType;
import com.common.entity.RPCRequest;
import com.common.entity.RPCResponse;
import com.common.exception.SerializeException;
import com.common.serialize.CommonSerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author Zixiang Hu
 * @description 自定义netty的解码器
 * @create 2021-03-01-14:27
 */
@Slf4j
public class MyNettyDecoder extends ReplayingDecoder<Void> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 首先读取消息的类型，是请求消息还是响应消息
        int msgType = in.readInt();
        Class<?> msgClazz = null;
        if (msgType == MessageType.REQUEST.getCode()) {
            msgClazz = RPCRequest.class;
        } else if (msgType == MessageType.RESPONSE.getCode()) {
            msgClazz = RPCResponse.class;
        }
        // 获取序列化的方式
        int serializerType = in.readInt();
        CommonSerializer serializer = CommonSerializer.getByCode(serializerType);
        if (serializer == null) {
            log.error("序列化方式不存在");
            throw new SerializeException("序列化方式不存在");
        }
        // 获取消息真正的字节长度
        int byteLen = in.readInt();
        byte[] content = new byte[byteLen];
        in.readBytes(content);
        // 反序列化
        Object obj = serializer.deserialize(content, msgClazz);
        out.add(obj);
    }
}
